package com.aliyun.messagemgt.repository.task;

import com.aliyun.messagemgt.util.SmsQuotaDateUtils;
import com.aliyun.messagemgt.common.constants.SmsQuotaConstant;
import com.aliyun.messagemgt.dto.SmsQuota;
import com.aliyun.messagemgt.dto.SmsQuotaMonitor;
import com.aliyun.messagemgt.dto.SmsQuotaRenew;
import com.aliyun.messagemgt.domain.repository.SmsQuotaMonitorRepository;
import com.aliyun.messagemgt.domain.repository.SmsQuotaRenewRepository;
import com.aliyun.messagemgt.domain.repository.SmsQuotaRepository;
import com.aliyun.messagemgt.domain.repository.task.BaseTask;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 每月1号巡检未生效的短信配额
 *
 * @author byp
 * @date 2020/7/21
 */
@DisallowConcurrentExecution
@Component
public class PollingUnEffectiveTask implements BaseTask {

    @Resource
    private SmsQuotaRepository smsQuotaRepository;
    @Resource
    private SmsQuotaMonitorRepository smsQuotaMonitorRepository;
    @Resource
    private SmsQuotaRenewRepository smsQuotaRenewRepository;

    private final Logger logger = LoggerFactory.getLogger(PollingUnEffectiveTask.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("将上月/年续订额度置为失效 begin");
        //必须先执行这部分内容再巡检未生效的
        this.executeRenewQuota();
        logger.info("将上月/年续订额度置为失效 end");

        logger.info("巡检未生效的短信配额 begin");
        //查询未生效配置列表
        List<SmsQuota> quotaList = smsQuotaRepository.queryQuotaByStatus(SmsQuotaConstant.EFFECTIVE_STATUS_WEISHENGXIAO);
        if (CollectionUtils.isEmpty(quotaList)) {
            logger.info("未查到次月/年生效的数据");
            return;
        }
        for (SmsQuota smsQuota : quotaList) {
            if (SmsQuotaConstant.QUOTA_TYPE_YEAR.equals(smsQuota.getQuotaType()) && SmsQuotaDateUtils.currentIntMonth() != 1) {
                continue;
            }
            //1.1先查询有效的这条数据，把这条数据更新为失效。
            SmsQuota effective = smsQuotaRepository.queryQuotaByMsgSourceIdAndStatus(smsQuota.getMsgSourceId(), SmsQuotaConstant.EFFECTIVE_STATUS_SHENGXIAO);
            effective.setEffectiveStatus(SmsQuotaConstant.EFFECTIVE_STATUS_SHIXIAO);
            smsQuotaRepository.update(effective);
            //1.2处理告警逻辑
            this.executeMonitorInfo(smsQuota);
            //1.3更新这条未生效的数据
            smsQuota.setEffectiveStatus(SmsQuotaConstant.EFFECTIVE_STATUS_SHENGXIAO);
            smsQuota.setEffectiveType(SmsQuotaConstant.EFFECTIVE_TYPE_NOW);
            smsQuotaRepository.update(smsQuota);
        }
        logger.info("巡检未生效的短信配额 end");


    }

    /**
     * 将上月/年续订额度置为失效
     */
    private void executeRenewQuota() {
        List<SmsQuota> quotaList = smsQuotaRepository.queryQuotaByStatus(SmsQuotaConstant.EFFECTIVE_STATUS_SHENGXIAO);

        if (CollectionUtils.isNotEmpty(quotaList)) {
            for (SmsQuota smsQuota : quotaList) {
                Integer quotaType = smsQuota.getQuotaType();
                List<SmsQuotaRenew> renewList;
                SmsQuotaRenew query = new SmsQuotaRenew();
                query.setMsgSourceId(smsQuota.getMsgSourceId());
                if (SmsQuotaConstant.QUOTA_TYPE_YEAR.equals(quotaType)) {
                    //年度
                    query.setRenewYear(SmsQuotaDateUtils.lastYear());
                    renewList = smsQuotaRenewRepository.queryRenewListByEntity(query);
                } else {
                    String lastMonth = SmsQuotaDateUtils.lastMonth();
                    query.setRenewMonth(lastMonth);
                    if ("12".equals(lastMonth)) {
                        query.setRenewYear(SmsQuotaDateUtils.lastYear());
                    } else {
                        query.setRenewYear(SmsQuotaDateUtils.currentYear());
                    }
                    renewList = smsQuotaRenewRepository.queryRenewListByEntity(query);
                }
                if (CollectionUtils.isNotEmpty(renewList)) {
                    for (SmsQuotaRenew renew : renewList) {
                        renew.setStatus(2);
                        smsQuotaRenewRepository.update(renew);
                    }
                }
            }
        }
    }

    /**
     * 处理告警信息
     *
     * @param smsQuota 次月/年生效配置
     */
    private void executeMonitorInfo(SmsQuota smsQuota) {
        //查询monitor是否存在告警信息
        SmsQuotaMonitor smsQuotaMonitor = smsQuotaMonitorRepository.selectMonitorByMsgSourceIdAndStatus(smsQuota.getMsgSourceId(), null);
        if (smsQuota.getMonitorMarginQuota() != null) {
            logger.info("短信配额表有告警配置");
            if (smsQuotaMonitor == null) {
                logger.info("没有查到告警配置，新增");
                SmsQuotaMonitor insert = new SmsQuotaMonitor().setMsgSourceId(smsQuota.getMsgSourceId())
                        .setMonitorQuota(smsQuota.getMonitorMarginQuota())
                        .setStatus(1)
                        .setCreateTime(new Date());
                smsQuotaMonitorRepository.insert(insert);
            } else {
                logger.info("查到告警配置，更新");
                smsQuotaMonitor.setStatus(1).setMonitorQuota(smsQuota.getMonitorMarginQuota())
                        .setUpdateTime(new Date());
                smsQuotaMonitorRepository.update(smsQuotaMonitor);
            }
        } else {
            logger.info("短信配额没有设置告警配置");
            //查询是否存在告警信息
            if (smsQuotaMonitor != null) {
                logger.info("删除已存在的告警信息");
                smsQuotaMonitorRepository.delete(smsQuota.getMsgSourceId());
            }
        }
    }

    @Override
    public String getName() {
        return "PollingUnEffectiveTask";
    }

    @Override
    public String getGroup() {
        return "PollingUnEffectiveTask";
    }
}
